/**
 * @author huangmy
 * @text   员工管理
 */

Ext.extend(CQCIS.module, {
    init: function() {
    	// 页面列表
        var listMeta = [{
            id: 'staffId',
            field: 'staffId',
            desc: '员工ID',
            hidden: true
        }, {
            field: 'staffName',
            desc: '员工名称',
            width: 100
        }, {
        	field: 'sex',
        	desc: '性别',
        	width: 100
        }, {
            field: 'placeId',
            desc: '职位',
            width: 100
        }, {
            field: 'age',
            desc: '年龄',
            width: 100
        }, {
            field: 'birthday',
            desc: '生日',
            type: 'date',
            width: 100
        }, {
            field: 'cardType',
            desc: '证件类型',
            width: 100
        }, {
            field: 'cardNo',
            desc: '证件号码',
            width: 100
        }, {
            field: 'regionId',
            desc: '组织ID',
            width: 100,
            renderer: function(value) {
                regionDwr.getRegion(value, {
                    callback: function(region) {
                        if (region) {
                            value = region.regionName;
                        } else {
                            value = '未知组织';
                        }
                    },
                    async: false
                });
                
                return value;
            }
        }, {
            field: 'departId',
            desc: '部门ID',
            renderer: function(value) {
                regionDwr.getDepart(value, {
                    callback: function(region) {
                        if (region) {
                            value = region.departName;
                        } else {
                            value = '未知部门';
                        }
                    },
                    async: false
                });
                
                return value;
            }
        }, {
            field: 'staffType',
            desc: '员工类型',
            width: 100,
            renderer: function(value) {
                var str = "";
                switch (value) {
                    case '1':
                        str = "管理员工";
                        break;
                    case '2':
                        str = "医院员工";
                        break;
                    case '3':
                        str = "血站员工";
                        break;
                }
                return str;
            }
        }, {
            field: 'relaPhone',
            desc: '联系电话',
            width: 100
        }, {
            field: 'relaMobile',
            desc: '移动电话',
            width: 100
        }, {
            field: 'otherRelaPhone',
            desc: '其他联系电话',
            width: 100
        }, {
            field: 'relaAddr',
            desc: '联系地址',
            width: 100
        }, {
            field: 'email',
            desc: 'EMAIL',
            width: 100
        }, {
            field: 'state',
            desc: '状态',
            width: 60,
            renderer: function(value) {
                var str = "";
                switch (value) {
                    case '0':
                        str = "离职";
                        break;
                    case '1':
                        str = "正常";
                        break;
                    case '2':
                        str = "休假";
                        break;
                }
                return str;
            }
        }];
        
        // 增加
        var staffMeta = [{
            id: 'staffId',
            name: 'staffId',
            fieldLabel: 'ID',
            xtype: 'hidden'
        }, {
            name: 'staffName',
            fieldLabel: '员工名称',
            allowBlank: false,
            regex: /^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$/,
            regexText: '团队名称只能由中文、英文或数字组成'
        }, {
            name: 'sex',
            fieldLabel: '性别',
            store: [['1', '男'], ['2', '女'], ['0', '未知']],
            triggerAction: 'all',
            mode: 'local',
            allowBlank: false,
            editable: false,
            xtype: 'combo',
            value: '1'
        }, {
            hiddenName: 'placeId',
            fieldLabel: '职位',
            store: [['1', '主任'], ['2', '职工']],
            triggerAction: 'all',
            mode: 'local',
            allowBlank: false,
            editable: false,
            xtype: 'combo',
            value: 1
        }, {
            name: 'age',
            fieldLabel: '年龄'
        }, {
            name: 'birthday',
            fieldLabel: '生日',
            xtype: 'datefield'
        }, {
            name: 'cardType',
            fieldLabel: '证件类型',
            store: [['1', '身份证'], ['2', '职工证']],
            triggerAction: 'all',
            mode: 'local',
            allowBlank: false,
            editable: false,
            xtype: 'combo',
            value: 1
        }, {
            name: 'cardNo',
            fieldLabel: '证件号码'
        }, {
            name: 'regionId',
            fieldLabel: '所属组织',
            fields: ['regionId', 'regionName'],
            valueField: 'regionId',
            displayField: 'regionName',
            ds: {
                call: regionDwr.getAllRegions
            },
            xtype: 'rcombo'
        }, {
            name: 'departId',
            fieldLabel: '所属部门',
            fields: ['departId', 'departName'],
            valueField: 'departId',
            displayField: 'departName',
            ds: {
                call: regionDwr.getDeparts
            },
            xtype: 'rcombo'
        }, {
            name: 'staffType',
            fieldLabel: '员工类型',
            store: [['1', '管理员工'], ['2', '医院员工'], ['3', '血站员工']],
            triggerAction: 'all',
            mode: 'local',
            allowBlank: false,
            editable: false,
            xtype: 'combo',
            value: 1
        }, {
            name: 'relaPhone',
            fieldLabel: '联系电话',
            regex: /^(\d{8,8}|\d{11,11})$/,
            regexText: '电话8位或11位'
        }, {
            name: 'relaMobile',
            fieldLabel: '移动电话',
            regex: /^(\d{8,8}|\d{11,11})$/,
            regexText: '电话8位或11位'
        }, {
            name: 'otherRelaPhone',
            fieldLabel: '其他联系电话',
            regex: /^(\d{8,8}|\d{11,11})$/,
            regexText: '电话8位或11位'
        }, {
            name: 'relaAddr',
            fieldLabel: '联系地址'
        }, {
            name: 'email',
            fieldLabel: 'EMAIL'
        }, {
            fieldLabel: '状态',
            name: 'state',
            value: '1',
            xtype: 'hidden'
        }];
        
        // 员工信息窗口
        var staffWin = new CQCIS.Window({
            id: 'sm_staff_teamWin',
            title: '员工信息',
            height: 520,
            items: new CQCIS.form.DWRForm({
                labelWidth: 70,
                dwr: {
                    load: staffDwr.getStaff,
                    save: staffDwr.createStaff,
                    update: staffDwr.updateStaff
                },
                items: staffMeta,
                afterSubmit: function(teamId) {
                    grid.refresh();
                }
            })
        });
        
        // 组织下拉框
        var cbxRegion = new CQCIS.form.TreeComboBox({
            dwrCall: regionDwr.getRegions,
            displayField: 'regionName',
            valueField: 'regionId',
            rootText: '组织',
            emptyText: '请选择组织',
            width: 100,
            listWidth: 250,
            treeListeners: {
                'beforeload': function(node) {
                    if (node.isRoot) {
                        node.getUI().show();
                        node.ownerTree.loader.params = [0];
                    } else {
                        node.ownerTree.loader.params = [node.id];
                    }
                },
                'beforeselect': function() {
                	cbxDepart.reload();
                }
            }
        });
        
        //部门下拉框
        var cbxDepart = new CQCIS.form.DWRComboBox({
            fields: ['departId', 'departName'],
            valueField: 'departId',
            displayField: 'departName',
            ds: {
                call: regionDwr.getDepartsByRegionId,
                params: [cbxRegion.getValue()]
            },            
            emptyText: '请选择部门'
        });
                
        // 工具栏查找按钮
        var searchBtn = new Ext.Toolbar.Button({
            text: '查询',
            iconCls: 'btn_insert',
            handler: function() {
                var regionText = cbxRegion.getValue();
                var departText = cbxDepart.getValue();
                
                grid.filter['regionId'] = regionText;
                grid.filter['departId'] = departText;
                
                grid.reload();
            }
        });
        
        // 工具栏增加按钮
        var addBtn = new Ext.Toolbar.Button({
            text: '增加',
            iconCls: 'btn_insert',
            handler: function() {
                staffWin.show();
            }
        });
        
        // 工具栏修改按钮
        var editBtn = new Ext.Toolbar.Button({
            text: '修改',
            iconCls: 'btn_modify',
            handler: function() {
                var menu = grid.getSelectedRow();
                if (menu) {
                    staffWin.load(menu.staffId);
                } else {
                    CQCIS.msg('请选择要修改的记录!');
                }
            }
        });
        
        // 工具栏删除按钮
        var delBtn = new Ext.Toolbar.Button({
            text: '删除',
            iconCls: 'btn_config',
            handler: function() {
                var menu = grid.getSelectedRow();
                if (menu) {
                    Ext.Msg.confirm('操作提示', '确定要删除选择的员工，员工删除后将无法恢复?', function(param) {
                        if (param == 'yes') {
                            staffDwr.deleteStaff(menu.staffId, function() {
                                CQCIS.msg("选定的记录操作成功!");
                                grid.refresh();
                            });
                        }
                    });
                } else {
                    CQCIS.msg("请选择要操作的记录!");
                }
            }
        });
        
        // 增加
        var workerMeta = [{
            id: 'loginId',
            name: 'loginId',
            fieldLabel: 'ID',
            xtype: 'hidden'
        }, {
            name: 'loginCode',
            fieldLabel: '登录工号',
            allowBlank: false,
            regex: /^[A-Za-z0-9]+$/,
            regexText: '工号只能由英文或数字组成',
            enableKeyEvents: true,
            listeners: {
                'keyup': function(o) {
                    o.setValue(o.getValue().toUpperCase());
                },
                'blur': function() {
                    if (workerWin.find('name', 'loginCode')[0].isValid() == true) {
                        workerDwr.getWorkersByLoginCode(workerWin.getBasicForm().getValues().loginCode, function(lv) {
                            if (lv && lv.length > 0) {
                                CQCIS.msg('该组织编码已存在,请重新输入!');
                                workerWin.find('name', 'loginCode')[0].reset();
                                return false;
                            }
                        })
                    }
                }
            }
        }, {
            name: 'staffId',
            fieldLabel: '员工ID',
            xtype: 'hidden'
        }, {
            name: 'loginPwd',
            fieldLabel: '登录密码',
            allowBlank: false,
            regex: /^[A-Za-z0-9]+$/,
            regexText: '工号只能由英文或数字组成'
        }, {
            name: 'loginType',
            fieldLabel: '登录级别',
            xtype: 'hidden'
        }, {
            name: 'sendPhone',
            fieldLabel: '发送短信号码',
            regex: /^(\d{8,8}|\d{11,11})$/,
            regexText: '电话8位或11位'
        }, {
            name: 'loginNum',
            fieldLabel: '登录次数',
            xtype: 'hidden'
        }, {
            name: 'lastChgPwdTime',
            fieldLabel: '最后一次修改密码时间',
            type: 'date',
            xtype: 'hidden'           
        }, {
            fieldLabel: '状态',
            name: 'state',
            xtype: 'hidden',
            value: '1'
        }];
        
        var dwrForm = new CQCIS.form.DWRForm({
            labelWidth: 100,
            dwr: {
                load: workerDwr.getWorker,
                save: function() {
                    var values = workerWin.getBasicForm().getValues();                        
                    values.staffId = grid.getSelectedRow().staffId;
                    workerDwr.createWorker(values, function() {
                        CQCIS.msg('工号添加成功，请到“工号管理”中进行查询、修改');
                        dwrForm.afterRemote();
                        workerWin.hide();
                    });
                },
                update: workerDwr.updateWorker
            },
            items: workerMeta
        });
        
        // 员工信息窗口
        var workerWin = new CQCIS.Window({
            id: 'sm_worker_staff_teamWin',
            title: '工号信息',
            height: 160,
            items: dwrForm,
            listeners: {
                'show': function(o) {
                    o.getForm().afterRemote();
                }
            }
        });
        
        // 工具栏增加工号按钮
        var addWorkerBtn = new Ext.Toolbar.Button({
            text: '添加工号',
            iconCls: 'btn_insert',
            handler: function() {
                var staff = grid.getSelectedRow();
                if (staff) {
                	// 判断是否已经有工号
                	workerDwr.getWorkersByStaffId(staff.staffId, {
                		callback: function(workers) {
                			if (workers && workers.length > 0) {
                				Ext.Msg.confirm('操作提示', '该员工已经有工号存在，继续添加新的工号吗？', function(param) {
			                        if (param == 'yes') {
			                            workerWin.show();
			                        }
			                    });
                			} else {
                				workerWin.show();
                			}
                		},
                		async: false
                	});                    
                } else {
                    CQCIS.msg("请选择要操作的记录!");
                }
            }
        });
        
        // 员工信息grid
        var grid = new CQCIS.grid.PageGrid({
            id: 'sm_staff_grid',
            firstColumn: 'radio',
            dwr: {
                call: staffDwr.pageStaffs
            },
            metas: listMeta,
            tbar: ['组织:', cbxRegion, '-', '部门:', cbxDepart, searchBtn, addBtn, editBtn, delBtn, addWorkerBtn],
            bbar: 'true'
        });
        
        // 定义关联销毁对象数组，避免内存泄漏
        this.main.associatedComp = [staffWin, workerWin];
        // 定义页面主元素
        this.main.add(grid);
        // 布局更新
        this.main.doLayout();
    }
});
